package com.test.clyq.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.google.gson.Gson;
import com.test.clyq.entity.CategoryImg;
import com.test.clyq.entity.DownloadFileIos;
import com.test.clyq.entity.EntityItem;
import com.test.clyq.entity.PicturesIos;
import com.test.clyq.service.CategoryImgService;
import com.test.clyq.service.EntityItemService;
import com.test.json.JsonUtil;
import com.test.util.FormatExceptionStack;
import com.test.util.ObjectUtils;
import com.test.util.Pagination;
import com.test.util.StringUtils;
import com.test.webapp.action.BaseAction;

/**
 * IpadEntityItemAction. <br>
 * 内容管理.
 * <p>
 * Copyright: Copyright (c) 2011-8-02 下午03:49:58
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: liuxl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class IpadEntityItemAction extends BaseAction {

	/**
	 * 根据文章ID获取文章实体
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getEntityItemById(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws Exception {
		String entityId = getParameter(request, "entityId");
		EntityItem entityItem = null;
		EntityItemService entityItemService = (EntityItemService) getBean("entityItemService");
		if (!ObjectUtils.isNull(entityId)) {
			entityItem = entityItemService.getEntityItemById(Long.valueOf(entityId));
		}
		if (!ObjectUtils.isNull(entityItem) && entityItem.getEntityItemId() != null) {

		} else {
			entityItem = null;
		}
		String json = entityItem == null ? "" : entityItem.getEntityContent();
		print(response, json, null, null);

		return null;
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * ipad获取实体列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward showEntitysByCId(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws Exception {
		try {
			EntityItemService entityItemService = (EntityItemService) getBean("entityItemService");
			// 栏目id
			String maxId = request.getParameter("maxId");
			String minId = request.getParameter("minId");
			String cId = getParameter(request, "cId");
			Integer count = (getParameter(request, "count") != null) ? Integer.parseInt(getParameter(request, "count")) : 10;

			List<EntityItem> list2 = new ArrayList<EntityItem>();
			List<String> whereList = new ArrayList<String>();
			List<String> orderList = new ArrayList<String>();
			orderList.add(" entityitem.entityCreatetime desc");
			orderList.add(" entityitem.id desc");

			if (maxId != null && !"".equals(maxId)) {
				whereList.add(" entityitem.id > " + maxId);
				list2 = entityItemService.getEntityItemListByParentCategoryId(Long.valueOf(cId), new Pagination(1, count), whereList, orderList);
			} else if (minId != null && !"".equals(minId)) {
				whereList.add(" entityitem.id < " + minId);
				list2 = entityItemService.getEntityItemListByParentCategoryId(Long.valueOf(cId), new Pagination(1, count), whereList, orderList);
			} else {
				list2 = entityItemService.getEntityItemListByParentCategoryId(Long.valueOf(cId), new Pagination(1, count), whereList, orderList);
			}

			String json = JsonUtil.getJsonStr(list2, new String[] { "id", "entityCreatetime", "entityImgUrl", "entityName", "detailUrl",
			        "convertUrl", "price", "entityImgs" }, -1);

			print(response, json, null, null);
			return null;
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
			log.info(e.getMessage());
		}
		return null;

	}

	/**
	 * ipad通过栏目id获取图片列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward showEntitysImgByCategoryId(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws Exception {
		try {
			EntityItemService entityItemService = (EntityItemService) getBean("entityItemService");
			// 栏目id
			String maxId = request.getParameter("maxId");
			String minId = request.getParameter("minId");
			String cId = getParameter(request, "cId");
			Integer count = (getParameter(request, "count") != null) ? Integer.parseInt(getParameter(request, "count")) : 10;

			List<EntityItem> list = new ArrayList<EntityItem>();
			List<String> whereList = new ArrayList<String>();
			List<String> orderList = new ArrayList<String>();
			orderList.add(" entityitem.entityCreatetime desc");
			orderList.add(" entityitem.id desc");
			if (maxId != null && !"".equals(maxId)) {
				whereList.add(" entityitem.id > " + maxId);
				list = entityItemService.getEntityItemListByParentCategoryId(Long.parseLong(cId), new Pagination(1, count), whereList, orderList);
			} else if (minId != null && !"".equals(minId)) {
				whereList.add(" entityitem.id < " + minId);
				list = entityItemService.getEntityItemListByParentCategoryId(Long.valueOf(cId), new Pagination(1, count), whereList, orderList);
			} else {
				list = entityItemService.getEntityItemListByParentCategoryId(Long.parseLong(cId), new Pagination(1, count), whereList, orderList);
			}

			List<DownloadFileIos> tempList = new ArrayList<DownloadFileIos>();
			// 针对ipad所需的信息做转换

			if (list != null) {

				for (EntityItem entityItem : list) {
					DownloadFileIos dIos = new DownloadFileIos();
					List<PicturesIos> pList = new ArrayList<PicturesIos>();

					dIos.setId(entityItem.getEntityItemId());
					// dIos.setDesc(StringUtils.isEmpty(entityItem.getEntityDesc())
					// ? "" : entityItem.getEntityDesc());
					dIos.setName(entityItem.getEntityName());
					dIos.setConvertUrl(entityItem.getConvertUrl() != null ? entityItem.getConvertUrl() : "");
					dIos.setCreateTime(entityItem.getEntityCreatetime());
					dIos.setSubTitle("");
					if (!StringUtils.isEmpty(entityItem.getEntityImgUrl())) {
						dIos.setImage(entityItem.getEntityImgUrl() + "_670x670.jpg");

					} else {
						dIos.setImage("");
					}
					dIos.setCatId(entityItem.getEntityCategoryId());
					dIos.setBasicCreateTime(entityItem.getEntityCreatetime());

					String picStr = entityItem.getEntityImgs();
					if (picStr != null && !"".equals(picStr)) {
						String[] pics = picStr.split(",");
						if (pics != null) {
							int order = 1;
							for (String str : pics) {
								if (StringUtils.isEmpty(str)) {
									str = "";
								}

								PicturesIos pIos = new PicturesIos();
								pIos.setOrder(order);
								pIos.setImage(str);
								pList.add(pIos);
								order++;
							}
						}
					}

					dIos.setPictures(pList);
					dIos.setLocation(0);
					dIos.setIpadOrder(0);
					dIos.setSubTitle(entityItem.getEntityName());
					tempList.add(dIos);
				}
			}
			Gson gson = new Gson();
			String json = gson.toJson(tempList);
			json = "{\"results\":" + json + "}";
			// 输出json
			print(response, json, null, null);
			return null;
		}
		catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return null;

	}

	/**
	 * 获得栏目域图片列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward getCategoryImgs(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("获得栏目域图片列表start");
		CategoryImgService categoryImgService = (CategoryImgService) getBean("categoryImgService");
		try {
			String start = getParameter(request, "start");
			String limit = getParameter(request, "limit");
			String categoryId = "0";
			Pagination pagination = null;
			if (StringUtils.isNumeric(start) && StringUtils.isNumeric(limit) && StringUtils.isNumeric(categoryId)) {
				int currpageNo = 1;
				int pageCount = Integer.parseInt(limit);
				if (Integer.parseInt(start) / pageCount != 0) {
					currpageNo = Integer.parseInt(start) / pageCount + 1;// 当前页码
				}
				pagination = new Pagination(currpageNo, pageCount);// 设置分页参数（页码和每页显示记录条数）

			} else {
				pagination = new Pagination(1, 3);// 设置分页参数（页码和每页显示记录条数）
			}
			List<CategoryImg> list = categoryImgService.getCategoryImgsByCategoryId(Long.valueOf(categoryId), pagination);

			Gson gson = new Gson();
			String json = gson.toJson(list);
			json = "{\"results\":" + json + "}";

			this.log.debug("获得栏目域图片列表成功");
			this.log.info("获得栏目域图片列表end");
			print(response, json, null, null);

		}
		catch (Exception e) {
			this.log.error("获得栏目域图片:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}
}